import api from '../../api/index'
import * as types from '../mutation-types';

const state = {
  themesList: [],

  themesTotal: 0,

  themeDetail: {},
  themeScrollTop: 0
}

const actions = {
  getThemesList({
    commit
  }, params) {

    api.get_themes_list(params).then(res => {
      commit(types.GET_THEMES_LIST, res)
    });
  },
  getThemeDetail({
    commit
  }, params) {
    api.get_theme_detail(params).then(res => {
      commit(types.GET_THEME_DETAIL, res)
    })
  },
  updateThemePosition({
    commit
  }, top) {
    commit({
      type: 'updateThemePosition',
      top: top
    })
  }
}

const getters = {
  themesList: state => state.themesList,

  themesTotal: state => state.themesTotal,

  themeDetail: state => state.themeDetail,
  themeScrollTop: state => state.themeScrollTop
}

const mutations = {
  [types.GET_THEMES_LIST](state, res) {
    if (res.code === 0) {
      state.themesList = []
      state.themesTotal = 0
    } else {
      if (res.data.data.length !== 0 && res.data.current_page !== 1) {
        let end = res.data.current_page * 10
        let start = end - 10
        for (start; start < end; start++) {
          if (start < res.data.total) {
            let newIndex = start % 10;
            state.themesList.push(res.data.data[newIndex])
          }
        }
      } else if (res.data.current_page == 1 && res.data.data.length !== 0) {
        state.themesList = res.data.data
        state.themesTotal = res.data.total
      }
    }
  },
  [types.GET_THEME_DETAIL](state, res) {
    if (res.code === 0) {
      state.themeDetail = {}
    } else {
      state.themeDetail = res.data
    }
  },
  updateThemePosition(state, payload) {
    state.themeScrollTop =  payload.top
  }
}

export default {
  state,
  actions,
  getters,
  mutations,
}
